package com.appspot.urlheap.tmpl;

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class TemplateProcessor {

	private static final Configuration cfg;

	static {
		cfg = new Configuration();
		try {
			String templateDir = System.getProperty("user.dir") + "/WEB-INF/tmpl";
			cfg.setDirectoryForTemplateLoading(new File(templateDir));
			cfg.setObjectWrapper(new DefaultObjectWrapper());
			//cfg.setEncoding(new Locale("ru_RU"), "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void process(String template, Map<String, Object> values, Writer out) throws IOException {
		Template temp;
		try {
			temp = cfg.getTemplate(template);
			//temp.setEncoding("UTF-8");
			temp.process(values, out);
		} catch (TemplateException e) {
			e.printStackTrace();
			throw new IOException("Template exception: " + e.getMessage());
		} finally {
			out.flush();
		}

	}

}
